package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.api.user.UserClientApi;
import com.zhentao.mapper.*;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.common.vo.FeedbackVo;
import com.zhentao.model.pay.pojo.*;
import com.zhentao.model.pay.vo.BalanceVo;
import com.zhentao.model.user.pojo.ApUser;
import com.zhentao.service.ApUserMembershipService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* @author 许文倩
* @description 针对表【ap_user_membership】的数据库操作Service实现
* @createDate 2024-07-10 08:50:56
*/
@Service
public class ApUserMembershipServiceImpl extends ServiceImpl<ApUserMembershipMapper, ApUserMembership>
    implements ApUserMembershipService{
    @Resource
    ApUserMembershipMapper apUserMembershipMapper;
    @Resource
    ApUserPaymentOrderMapper paymentOrderMapper;
    @Resource
    AdMembershipCardMapper cardMapper;
    @Resource
    UserClientApi userClientApi;
    @Resource
    ApUserVipMapper apUserVipMapper;
    @Resource
    WithdrawRuleMapper withdrawRuleMapper;
    @Resource
    ApUserFinancialDetailsMapper apUserFinancialDetailsMapper;

    @Transactional
    @Override
    public ResponseResult add(ApUserMembership userMembership) {
        //添加中间表
        apUserMembershipMapper.insert(userMembership);
        //添加订单表
        QueryWrapper<AdMembershipCard> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(AdMembershipCard::getId,userMembership.getMembershipId());
        AdMembershipCard adMembershipCard = cardMapper.selectOne(wrapper);
        if (adMembershipCard==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该vip卡类型不存在");
        }
        //判断订单表中的是否已经购买过此卡（若购买过，购买次数加一）
        QueryWrapper<ApUserPaymentOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ApUserPaymentOrder::getMembershipId,userMembership.getMembershipId());
        queryWrapper.lambda().eq(ApUserPaymentOrder::getUserId,userMembership.getUserId());
        ApUserPaymentOrder apUserPaymentOrder1 = paymentOrderMapper.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(apUserPaymentOrder1)){
            apUserPaymentOrder1.setPaycount(apUserPaymentOrder1.getPaycount()+1);
            apUserPaymentOrder1.setCreatedTime(new Date());
            paymentOrderMapper.updateById(apUserPaymentOrder1);
        }else {
            ApUserPaymentOrder userPaymentOrder=new ApUserPaymentOrder();
            userPaymentOrder.setUserId(userMembership.getUserId());
            userPaymentOrder.setMoney(adMembershipCard.getMembershipPrice());
            userPaymentOrder.setMembershipId(adMembershipCard.getId());
            userPaymentOrder.setRemark(adMembershipCard.getMembershipDesc());
            userPaymentOrder.setPaycount(1);
            userPaymentOrder.setCreatedTime(new Date());
            paymentOrderMapper.insert(userPaymentOrder);
        }
        //更新用户身份
        userClientApi.updateApUser(userMembership);
        //添加用户身份过期时间表

        QueryWrapper<ApUserVip> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.lambda().eq(ApUserVip::getUserId,userMembership.getUserId());
        ApUserVip apUserVip1 = apUserVipMapper.selectOne(queryWrapper1);
        if (!ObjectUtils.isEmpty(apUserVip1)){
            Calendar calendar1=Calendar.getInstance();
            calendar1.setTime(apUserVip1.getPastTime());
            calendar1.add(Calendar.MONTH,adMembershipCard.getMembershipTime());
            Date time1 = calendar1.getTime();
            apUserVip1.setPastTime(time1);
            apUserVipMapper.updateById(apUserVip1);
        }else {
            long timeStamp = System.currentTimeMillis();
            Date date = new Date(timeStamp);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MONTH,adMembershipCard.getMembershipTime());
            Date time = calendar.getTime();
            ApUserVip apUserVip=new ApUserVip();
            apUserVip.setUserId(userMembership.getUserId());
            apUserVip.setPastTime(time);
            apUserVipMapper.insert(apUserVip);
        }
        //添加用户提成
        ApUser apUser = userClientApi.selectOne(userMembership.getUserId());
        //查询用户订单
        QueryWrapper<ApUserPaymentOrder> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.lambda().eq(ApUserPaymentOrder::getMembershipId,userMembership.getMembershipId());
        queryWrapper2.lambda().eq(ApUserPaymentOrder::getUserId,userMembership.getUserId());
        ApUserPaymentOrder apUserPaymentOrder = paymentOrderMapper.selectOne(queryWrapper);
        //判断用户是否绑定推荐人
        if (!ObjectUtils.isEmpty(apUser.getReferrerId())){
            ApUserFinancialDetails financialDetails=new ApUserFinancialDetails();
            //查询推荐人身份
            ApUser apUser1 = userClientApi.selectOne(apUser.getReferrerId());
            List<WithdrawRule> withdrawRules = withdrawRuleMapper.selectList(null);
            //根据身份循环获取提成
            for (WithdrawRule withdrawRule:withdrawRules){
                if (apUser1.getIdentity().equals(withdrawRule.getIdentity())){
                    if (userMembership.getMembershipId().equals(3)){
                        financialDetails.setUserId(apUser.getReferrerId());
                        financialDetails.setMoney( adMembershipCard.getMembershipPrice()*withdrawRule.getVipRule()*apUserPaymentOrder.getPaycount());
                        financialDetails.setDType(0);
                        financialDetails.setOrderId(apUserPaymentOrder.getId());
                        financialDetails.setAuditStatus(0);
                        financialDetails.setCreatedTime(new Date());
                        financialDetails.setAuditStatus(1);

                    }else {
                        financialDetails.setUserId(apUser.getReferrerId());
                        financialDetails.setMoney( adMembershipCard.getMembershipPrice()*withdrawRule.getMatchmakerRule()*apUserPaymentOrder.getPaycount());
                        financialDetails.setDType(0);
                        financialDetails.setOrderId(apUserPaymentOrder.getId());
                        financialDetails.setAuditStatus(0);
                        financialDetails.setCreatedTime(new Date());
                        financialDetails.setAuditStatus(1);
                    }
                    apUserFinancialDetailsMapper.insert(financialDetails);
                }
            }
            //修改用户账户余额
            QueryWrapper<ApUserFinancialDetails> wrapper1=new QueryWrapper<>();
            wrapper1.lambda().eq(ApUserFinancialDetails::getUserId,apUser1.getId());
            List<ApUserFinancialDetails> apUserFinancialDetails = apUserFinancialDetailsMapper.selectList(wrapper1);
            double sum=0;
            for (ApUserFinancialDetails financialDetail:apUserFinancialDetails){
                sum+=financialDetail.getMoney();
            }
            apUser1.setBalance(sum);
            userClientApi.updateUser(apUser1);
        }
        return ResponseResult.okResult("充值成功");
    }

    @Override
    public ResponseResult outMoney(BalanceVo balanceVo) {
        ApUser apUser = userClientApi.selectOne(balanceVo.getUserId());
        if (apUser.getBalance() < balanceVo.getOutMoney()){
            return ResponseResult.errorResult(301,"余额不足，不可提现");
        }
        ApUserFinancialDetails apUserFinancialDetails=new ApUserFinancialDetails();
        apUserFinancialDetails.setUserId(balanceVo.getUserId());
        apUserFinancialDetails.setAuditStatus(0);
        apUserFinancialDetails.setDType(1);
        apUserFinancialDetails.setMoney(balanceVo.getOutMoney());
        apUserFinancialDetails.setCreatedTime(new Date());
        apUserFinancialDetailsMapper.insert(apUserFinancialDetails);
        return ResponseResult.okResult("提现申请已提交，待审核");
    }

    @Override
    public ResponseResult getFeedback(Integer userId) {
        List<FeedbackVo> feedback= apUserFinancialDetailsMapper.getFeedback(userId);
        return ResponseResult.okResult(feedback);
    }

}




